﻿#Region "Copyright"

' Copyright 2007 Ben Reichelt - http://benreichelt.net
' 
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
' 
'     http://www.apache.org/licenses/LICENSE-2.0
' 
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.


#End Region

Imports System.Configuration

Public Class SqlMetal

    Private _context As AppContext

    Public Sub New(ByVal context As AppContext)
        _context = context
    End Sub

    Public Function CreateXmlMetaDataFile() As XmlMetaData

        Dim credentials As String = ""

        If Not String.IsNullOrEmpty(_context.UserName) Then
            credentials = "/user:" & _context.UserName & " /password:" & _context.Password
        End If

        Dim args As String = "/server:" & _context.Server & " /database:" & _context.Database & " " & credentials & "  /xml:" & _context.OutputXmlFilePath

        _context.Logger.WriteLine("Generating SqlMetal xml using command line: """ & _context.SqlMetalLocation & " " & args & """")
        _context.Logger.WriteLine("")

        Dim p As New Process
        p.StartInfo = New ProcessStartInfo(_context.SqlMetalLocation, args)
        p.StartInfo.UseShellExecute = Not p.StartInfo.UseShellExecute
        p.Start()
        p.WaitForExit()

        ' copy the original for comparisons later
        _context.Logger.WriteLine("Copying output to: " & _context.ArchiveFilePath)
        IO.File.Copy(_context.OutputXmlFilePath, _context.ArchiveFilePath, True)

        Return New XmlMetaData(_context.OutputXmlFilePath)
    End Function

    Public Sub CreateCodeFromXmlMetaData()

        Dim language As String = "csharp"
        If _context.Language = SqlPlastic.Language.VB Then
            language = "vb"
        End If

        Dim args As String = "/namespace:" & _context.GeneratedNamespace & " /code:" & _context.OutputCodeFilePath & " /language:" & language & " " & _context.OutputXmlFilePath

        _context.Logger.WriteLine("Converting xml to .net code using command line: """ & _context.SqlMetalLocation & " " & args & """")
        _context.Logger.WriteLine("")

        Dim p As New Process
        p.StartInfo = New ProcessStartInfo(_context.SqlMetalLocation, args)
        p.StartInfo.UseShellExecute = Not p.StartInfo.UseShellExecute
        p.Start()
        p.WaitForExit()
    End Sub

End Class
